package middleware

import (
	"bytes"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"time"
)

// 自定义一个结构体，实现
// gin.ResponseWriter interface
type responseWriter struct {
	gin.ResponseWriter
	b *bytes.Buffer
}

// 重写 Write([]byte) (int, error) 方法
func (w responseWriter) Write(b []byte) (int, error) {
	//向一个bytes.buffer中写一份数据来为获取body使用
	w.b.Write(b)
	//完成gin.Context.Writer.Write()原有功能
	return w.ResponseWriter.Write(b)
}

// LoggerMiddleware 日志中间件
func LoggerMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 开始时间
		timeBegin := time.Now().UnixNano()
		// 处理请求
		//log.Println("✅ log start")
		writer := responseWriter{
			c.Writer,
			bytes.NewBuffer([]byte{}),
		}
		c.Writer = writer

		c.Next()
		//log.Println("✅ log end")
		// 结束时间
		timeEnd := time.Now().UnixNano()

		// 计算请求处理时间
		timeCost := float64(timeEnd-timeBegin) / 1e9 * 1000

		// 记录日志
		log.WithFields(log.Fields{
			"method":        c.Request.Method,
			"path":          c.Request.URL.Path,
			"ip":            c.ClientIP(),
			"user_agent":    c.Request.UserAgent(),
			"time_cost":     timeCost,
			"status":        c.Writer.Status(),
			"size":          c.Writer.Size(),
			"response_body": writer.b.String(),
			//"response":
		}).Info("Request")
		log.Println("🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟩 结束 🟩🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦")
	}
}
